﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rmlife.Common;
using System.IO;
using Rmlife.Config;
namespace Rmlife.Web.Tools.Handlers
{
    /// <summary>
    /// SettingHandler 的摘要说明
    /// </summary>
    public class SettingHandler : IHttpHandler
    {
        string fileUploadUrl = MyComfiguration.GetStringAppSetting("AvatarImagePath");
        string fileupdload = WebConfigs.Paths.UploadRoot;
        public void ProcessRequest(HttpContext context)
        {
            #region 清除缓存
            context.Response.ContentType = "text/plain";
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Cache.SetLastModified(DateTime.Now);
            context.Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
            #endregion

            string opt = context.Request.QueryString["opt"];
            context.Response.Clear();
            switch (opt)
            {
                case "upload": uploadImage(context); break;
                case "progress": uploadProgress(context); break;
            }
            context.Response.Flush();
        }
        #region "图片上传处理"
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="context"></param>
        private void uploadImage(HttpContext context)
        {
            try
            {
                string msg = string.Empty;
                //得到上传的文件
                HttpPostedFile file = context.Request.Files["Filedata"];
                System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream);

                //if (file.ContentLength > 1024 * 1024)
                //{
                //    context.Response.Write("{\"error\":\"图片文件不能超过1M\"");
                //    return;
                //}
                string strTemp = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
                //自定义文件保存路径
                string strfilePath = fileupdload + "" + strTemp;

                string filepath = Utils.GetMapPath(strfilePath);

                string path = Path.GetDirectoryName(filepath);
                if (file != null)
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    //if (!File.Exists(filepath))
                    //    file.SaveAs(filepath);
                    //int targetWidth = img.Width;

                    int targetHeight = (int)(img.Height * 300 / img.Width);
                    if (targetHeight < 300)
                        targetHeight = 300;
                    PTImage.ZoomAuto220(file.InputStream, filepath, 300, targetHeight, "", "", 7);
                    //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                    msg = "{\"url\":\"" + Utils.UrlEncode(strfilePath) + "\",\"width\":\"120\",\"height\":\"" + targetHeight + "\"}";
                    context.Response.Write(msg);
                    return;
                }
                else
                {
                    //msg = "{\"status\":\"fail\"}";
                    context.Response.Write(msg);
                    return;
                }
            }
            catch
            {
                context.Response.Write("{\"error\":\"上传出错\"}");
                return;
            }
        }

        /// <summary>
        /// 上传图片并生成缩略图
        /// </summary>
        /// <param name="context"></param>
        private void uploadProgress(HttpContext context)
        {
            System.Drawing.Image image, image64, image48, image32, image16; //定义image类的对象
            string imagePath;//图片路径
            string imageType;//图片类型
            string imageName;//图片名称
            string fileName = "";//图片名称
            //提供一个回调方法,用于确定Image对象在执行生成缩略图操作时何时提前取消执行
            //如果此方法确定 GetThumbnailImage 方法应提前停止执行，则返回 true；否则返回 false
            System.Drawing.Image.GetThumbnailImageAbort callb = null;

            HttpPostedFile UploadImage = context.Request.Files["FileData"];
           //物理路径
           string uploadpath = HttpContext.Current.Server.MapPath(context.Request["folder"] + "\\");

            if (UploadImage != null)
            {
                //是否有目录，如没有就创建
                if (!Directory.Exists(uploadpath))
                {
                    Directory.CreateDirectory(uploadpath);
                }
                //客户端文件完全名称
                string filename = UploadImage.FileName;
                string extname = filename.Substring(filename.LastIndexOf(".") + 1);
                //为不重复，设置文件名
                fileName = Guid.NewGuid().ToString() + "." + extname;

                //context.Response.Write("1");
                context.Response.Write(fileName);
            }
            else
            {
                context.Response.Write("0");
            }

            string mPath;

            imagePath = UploadImage.FileName;
            //取得图片类型
            imageType = imagePath.Substring(imagePath.LastIndexOf(".") + 1);
            //取得图片名称
            imageName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1);
            Stream imgStream = UploadImage.InputStream;//流文件，准备读取上载文件的内容
            int imgLen = UploadImage.ContentLength;//上载文件大小

            //建立虚拟路径
            mPath = HttpContext.Current.Server.MapPath(context.Request["folder"]);
            //保存到虚拟路径
            UploadImage.SaveAs(mPath + "\\" + fileName);
            ////显示原图
            //imageSource.ImageUrl = "upFile/" + imageName;
            //为上传的图片建立引用
            image = System.Drawing.Image.FromFile(mPath + "\\" + fileName);

            //生成缩略图
            image64 = image.GetThumbnailImage(64, 64, callb, new System.IntPtr());
            //把缩略图保存到指定的虚拟路径
            image64.Save(HttpContext.Current.Server.MapPath(context.Request["folder"]) + "\\64_" + fileName);
            //释放image64对象的资源
            image64.Dispose();

            //生成缩略图
            image48 = image.GetThumbnailImage(48, 48, callb, new System.IntPtr());
            image48.Save(HttpContext.Current.Server.MapPath(context.Request["folder"]) + "\\48_" + fileName);
            image48.Dispose();

            //生成缩略图
            image32 = image.GetThumbnailImage(32, 32, callb, new System.IntPtr());
            image32.Save(HttpContext.Current.Server.MapPath(context.Request["folder"]) + "\\32_" + fileName);
            image32.Dispose();
            //生成缩略图
            image16 = image.GetThumbnailImage(16, 16, callb, new System.IntPtr());
            image16.Save(HttpContext.Current.Server.MapPath(context.Request["folder"]) + "\\16_" + fileName);
            image16.Dispose();

            //释放image对象占用的资源
            image.Dispose();
        }

        #endregion

        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }
    }
}